package com.catherine.mvp_base_component.zxing.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.catherine.mvp_base_component.R;
import com.catherine.mvp_base_component.base.BaseComActivity;
import com.catherine.mvp_base_component.utils.ActivityUtil;
import com.catherine.mvp_base_component.utils.LogUtil;
import com.catherine.mvp_base_component.utils.StrUtils;
import com.catherine.mvp_base_component.utils.ToastUtil;
import com.catherine.mvp_base_component.zxing.camera.CameraManager;
import com.catherine.mvp_base_component.zxing.decoding.CaptureActivityHandler;
import com.catherine.mvp_base_component.zxing.decoding.InactivityTimer;
import com.catherine.mvp_base_component.zxing.dialog.ScanAddressDialog;
import com.catherine.mvp_base_component.zxing.distinguish.ScanTools;
import com.catherine.mvp_base_component.zxing.view.ViewfinderView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Vector;

/**
 * Initial the camera
 *
 * @author Ryan.Tang
 */
public class CaptureActivity extends BaseComActivity implements Callback {

    private static final int REQUEST_CODE_SCAN_GALLERY = 100;
    public static final String IS_FROM_MAIN_PAGE = "isFromMainPage";
    public static final String MAIN_NET = "main_net";
    private boolean isFromMainPage = false;
    private int mainNet;//0only，1以太坊

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private ImageView back;
    private ImageButton btnFlash;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private ProgressDialog mProgress;
    private String photo_path;
    private Bitmap scanBitmap;
    //	private Button cancelScanButton;
    public static final int RESULT_CODE_QR_SCAN = 0xA1;
    public static final String INTENT_EXTRA_KEY_QR_SCAN = "qr_scan_result";
    public static final String ADDRESS_TYPE = "address_type";//1表示存储地址，2表示转账

    @Override
    protected int getLayoutId() {
        return R.layout.activity_scanner;
    }

    @Override
    protected void initView() {
        //ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);
        CameraManager.init(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_content);
        ImageView ivBack = findViewById(R.id.scanner_iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                finish();
                ActivityUtil.finishActivity(CaptureActivity.this);
            }
        });

        TextView tvAlbum = findViewById(R.id.scanner_tv_album);
        tvAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] permissions = new String[]{/*Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,*/ Manifest.permission.READ_EXTERNAL_STORAGE};
/*  todo  相册识别二维码  待完善，部分图片无法识别
                   if (checkPermissionRequest(CaptureActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    jump2Album();
                } else {
                    ToastUtil.showToast(getResources().getString(R.string.scan_to_open_read_write_permission));
                }*/
            }
        });

        btnFlash = (ImageButton) findViewById(R.id.btn_flash);
        btnFlash.setOnClickListener(flashListener);

//        back = (ImageView) findViewById(R.id.scanner_toolbar_back);
//        back.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
//		cancelScanButton = (Button) this.findViewById(R.id.btn_cancel_scan);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
    }

    @Override
    protected void initData() {
        Bundle args = getIntent().getExtras();
        if(args != null){
            isFromMainPage = args.getBoolean(IS_FROM_MAIN_PAGE,false);
            mainNet = args.getInt(MAIN_NET,0);
        }
    }

    static final int DEVICE_PHOTO_REQUEST = 90;
    static final int REQUEST_SHOW_TIME = 190;
    private void jump2Album() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, DEVICE_PHOTO_REQUEST);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.scanner_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //用户没有进行有效的设置操作，返回
        if (requestCode == Activity.RESULT_CANCELED) {
//            ToastUtil.showToast(AddDeviceActivity.this, R.string.cancel);
//            ToastUtil.show("主动关闭了有问题");
            return;
        }
        if (DEVICE_PHOTO_REQUEST == requestCode) {
            if (null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                String imagePath;
                Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                if (c != null) {
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    photo_path = c.getString(columnIndex);
                    c.close();

/*                    Intent intent = new Intent(this, ShowImgClickActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("img", photo_path);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, REQUEST_SHOW_TIME);*/

                    Bitmap bitmap = null;
                    bitmap = BitmapFactory.decodeFile(photo_path);
                    if(bitmap != null){
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight());
                        String resultString = ScanTools.scanBitmap(bitmap);
                        LogUtil.e("imagePath", "photo_path=" + photo_path + "-----------------------" + resultString);
                        if (StrUtils.isEmpty(resultString)) {
                            ToastUtil.showToast("图片识别失败");
                            return;
                        }
                        // todo  对扫描结果 resultString 进行操作


                        Intent resultIntent = new Intent();
                        resultIntent.putExtra(INTENT_EXTRA_KEY_QR_SCAN, resultString);
                        setResult(RESULT_CODE_QR_SCAN, resultIntent);
                        ActivityUtil.finishActivity(CaptureActivity.this);
                    } else {
                        ToastUtil.showToast("图片识别失败");
                        return;
                    }
                } else {
                    ToastUtil.showToast("图片路径为空");
                }
            }
            return;
        }
        if (REQUEST_SHOW_TIME == requestCode && ShowImgClickActivity.RESULT_SHOW_TIME == resultCode) {
            String resultString = data.getStringExtra("String");
            LogUtil.e("imagePath", "photo_path=" + photo_path + "-----------------------" + resultString);
            if (StrUtils.isEmpty(resultString)) {
                ToastUtil.showToast("图片识别失败");
                return;
            }

            // todo  对扫描结果 resultString 进行操作


            Intent resultIntent = new Intent();
            resultIntent.putExtra(INTENT_EXTRA_KEY_QR_SCAN, resultString);
            setResult(RESULT_CODE_QR_SCAN, resultIntent);
            ActivityUtil.finishActivity(CaptureActivity.this);
        }
    }

    private void dealimg(Bitmap obmp) {
//        Bitmap obmp = ((BitmapDrawable) (iv.getDrawable())).getBitmap();
        int width = obmp.getWidth();
        int height = obmp.getHeight();
        int[] data = new int[width * height];
        obmp.getPixels(data, 0, width, 0, 0, width, height);
        RGBLuminanceSource source = new RGBLuminanceSource(width, height, data);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        new QrCodeAsyncTask().execute(bitmap);
    }

    class QrCodeAsyncTask extends AsyncTask<BinaryBitmap, Void, Result> {

        @Override
        protected Result doInBackground(BinaryBitmap... params) {
            QRCodeReader reader = new QRCodeReader();
            Result result = null;
            try {
                result = reader.decode(params[0]);
            } catch (NotFoundException e) {
                e.printStackTrace();
            } catch (ChecksumException e) {
                e.printStackTrace();
            } catch (FormatException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(Result result) {
            super.onPostExecute(result);

            String text = result.getText();
            LogUtil.e("text", "QR CODE: " + text);
            ToastUtil.showToast(text);
        }
    }

    private String recode(String str) {
        String formart = "";

        try {
            boolean ISO = Charset.forName("ISO-8859-1").newEncoder()
                    .canEncode(str);
            if (ISO) {
                formart = new String(str.getBytes("ISO-8859-1"), "GB2312");
                LogUtil.e("1234      ISO8859-1", formart);
            } else {
                formart = str;
                LogUtil.e("1234      stringExtra", str);
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return formart;
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.scanner_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                surfaceView.setVisibility(View.VISIBLE);
            }
        }, 100);

        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        reSetHandler();
        CameraManager.get().closeDriver();
    }

    private void reSetHandler(){
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    /**
     * Handler scan result
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        //FIXME
        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(CaptureActivity.this, getResources().getString(R.string.scan_failed), Toast.LENGTH_SHORT).show();
        } else {

            // todo  对扫描结果 resultString 进行操作


            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString(INTENT_EXTRA_KEY_QR_SCAN, resultString);
            System.out.println("------CaptureActivity--------scanResult===" + resultString);
            // 不能使用Intent传递大于40kb的bitmap，可以使用一个单例对象存储这个bitmap
//            bundle.putParcelable("bitmap", barcode);
//            Logger.d("saomiao",resultString);
            resultIntent.putExtras(bundle);
            this.setResult(RESULT_CODE_QR_SCAN, resultIntent);
        }
        ActivityUtil.finishActivity(CaptureActivity.this);
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    private boolean isFlashOn = false;
    /**
     * 闪光灯开关按钮
     */
    private View.OnClickListener flashListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                boolean isSuccess = CameraManager.get().setFlashLight(!isFlashOn);
                if (!isSuccess) {
                    Toast.makeText(CaptureActivity.this, getResources().getString(R.string.scan_flash_light_on_failed), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (isFlashOn) {
                    // 关闭闪光灯
                    btnFlash.setImageResource(R.drawable.flash_off);
                    isFlashOn = false;
                } else {
                    // 开启闪光灯
                    btnFlash.setImageResource(R.drawable.flash_on);
                    isFlashOn = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private ScanAddressDialog scanAddressDialog = null;
    private void showAddressDialog(String address){
        if(scanAddressDialog == null) {
            scanAddressDialog = new ScanAddressDialog.Builder()
                    .setAddress(address)
                    .setClickListener(new ScanAddressDialog.ClickListener() {
                        @Override
                        public void saveAddress(String address) {
                            Intent resultIntent = new Intent();
                            resultIntent.putExtra(INTENT_EXTRA_KEY_QR_SCAN, address);
                            resultIntent.putExtra(ADDRESS_TYPE,1);//1表示存储地址
                            setResult(RESULT_CODE_QR_SCAN, resultIntent);
                            ActivityUtil.finishActivity(CaptureActivity.this);
                        }

                        @Override
                        public void transfer(String address) {
                            Intent resultIntent = new Intent();
                            resultIntent.putExtra(INTENT_EXTRA_KEY_QR_SCAN, address);
                            resultIntent.putExtra(ADDRESS_TYPE,2);//2表示转账
                            setResult(RESULT_CODE_QR_SCAN, resultIntent);
                            ActivityUtil.finishActivity(CaptureActivity.this);
                        }

                        @Override
                        public void onDissmiss() {
                            //重置扫描
                            reSetHandler();
                            onResume();
                        }
                    }).build();
        }
        if(!scanAddressDialog.isAdded())
            scanAddressDialog.show(mFragmentManager,ScanAddressDialog.TAG);
    }
}